﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using Microsoft.SharePoint.WebControls;

namespace Srs.Sample.UI
{
    public static class WebPartExtensions
    {
        /// <summary>
        /// Gets what should be the one and only Scriptmanager for a page at execution time.
        /// </summary>
        /// <param name="control">Control</param>
        /// <returns>ScriptManager</returns>
        public static ScriptManager GetScriptManager(this Control control)
        {
            ScriptManager scriptMan = ScriptManager.GetCurrent(control.Page);
            if (scriptMan == null)
            {
                scriptMan = new ScriptManager();
                scriptMan.ID = "scriptHandler";
                control.Controls.AddAt(0,scriptMan);
            }
            return scriptMan;

        }



        /// <summary>
        /// ensure Proper doPostBack() behaviour in Ajax as per WSS SDK 1.4
        /// </summary>
        public static void EnsurePanelFix(this Control control)
        {
            Page page = control.Page as Page;

            //if (page.Form != null)
            //{
            //    string formOnSubmitAtt = page.Form.Attributes["onsubmit"];
            //    if (formOnSubmitAtt == "return _spFormOnSubmitWrapper();")
            //    {
            //        page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";
            //    }
            //}
            //ScriptManager.RegisterStartupScript(
            //    control, 
            //    control.GetType(), 
            //    "UpdatePanelFixup", 
            //    "_spOriginalFormAction = document.forms[0].action; _spSuppressFormOnSubmitWrapper=true;", 
            //    true);

            if (page != null && page.Form != null)
            {
                String fixupScript = @"
                        _spBodyOnLoadFunctionNames.push(""_initFormActionAjax"");
                        function _initFormActionAjax()
                        {
                            if (_spEscapedFormAction == document.forms[0].action)
                            {
                                document.forms[0]._initialAction = document.forms[0].action;
                            }
                        }
                        var RestoreToOriginalFormActionCore = RestoreToOriginalFormAction;
                        RestoreToOriginalFormAction = function()
                        {
                            if (_spOriginalFormAction != null)
                            {
                                RestoreToOriginalFormActionCore();
                                document.forms[0]._initialAction = document.forms[0].action;
                            }
                        }";

                ScriptManager.RegisterStartupScript(
                    page,
                    page.GetType(),
                    "UpdatePanelFixup",
                    fixupScript,
                    true);
            }
        }



        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        public static void HandleException(this UpdatePanel updatePanel, Exception ex, ref bool errorFlag, bool clearControls)
        {
            errorFlag = true;
            updatePanel.LogException(ex);

            if (clearControls) 
                updatePanel.ContentTemplateContainer.Controls.Clear();
            else
                updatePanel.AddLineBreak();
            
            updatePanel.ContentTemplateContainer.Controls.Add(new LiteralControl(ex.Message));

        }

        /// <summary>
        /// Adds a simple HTML line break to the control collection
        /// </summary>
        /// <param name="control"></param>
        public static void AddLineBreak(this Control control)
        {
            Label t = new Label();
            t.Text = "</br>";
            control.Controls.Add(t);
        }

        /// <summary>
        /// Adds a simple HTML line break to the update panel
        /// </summary>
        /// <param name="updatePanel"></param>
        public static void AddLineBreak(this UpdatePanel updatePanel)
        {
            Label t = new Label();
            t.Text = "</br>";
            updatePanel.ContentTemplateContainer.Controls.Add(t);
        }

        public static SPGridView BuildGrid(this Control control, Type businessType)
        {
            Type[] typesEx = new Type[] { typeof(string), typeof(int?), typeof(int), typeof(System.Data.Linq.Binary) };

            var props = from prop in businessType.GetProperties()
                        select prop;

            List<PropertyInfo> props2 = (from p in props where typesEx.Contains(p.PropertyType) select p).ToList();

            SPGridView spGrid = new SPGridView();
            
            foreach (PropertyInfo objectProp in props2)
            {
                SPBoundField bndField = new SPBoundField();
                bndField.DataField = objectProp.Name;
                bndField.HeaderText = objectProp.Name;
                bndField.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
                spGrid.Columns.Add(bndField);
            }

            spGrid.AutoGenerateColumns = false;

            return spGrid;
        }


    }
}
